package com.powernode.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;

/**
 * 文件上传接口控制层
 */
@Api(tags = "文件上传接口管理")
@RequestMapping("admin/file")
@RestController
public class FileController {

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;


    /**
     * 上传功能：
     *  1.请求方式必须是POST请求
     *  2.后台接收文件使用的类型是SpringMVC的MultipartFile类型接口
     *
     *  admin/file/upload/element
     * @return
     */
    @ApiOperation("上传单个文件")
    @PostMapping("upload/element")
    public ResponseEntity<String> uploadFile(MultipartFile file) {
        // 以天为单位生成一个文件夹存放文件
        String newFolderName = DateUtil.format(new Date(), "yyyy-MM-dd");
        // 创建新文件名称
        String newFileName = DateUtil.format(new Date(), "HHmmssSSS");
        // 获取原文件的后缀名称
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = newFolderName+"/"+newFileName+fileSuffix;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        URL url = null;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 上传
            ossClient.putObject(putObjectRequest);

            // 生成访问当前上传文件的路径URL
            url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(), 365 * 10));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ResponseEntity.ok(url.toString());
    }
}
